<?php

namespace App\Admin\Forms\User;

use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Wen\Utils\Settings;
use App\Wen\Utils\UserUtils;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Cache;

class UserCoinForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理表单请求.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        global $__MINI_GLOBAL_TENANT_ID__;
        if($__MINI_GLOBAL_TENANT_ID__ > 0){
            return $this->response()
                ->error('无权限.');
        }

        $id = $input['id'];
        $add_coin = (int)($input['add_coin']);
        if($add_coin == 0){
            return $this->response()
                ->warning('增加或减少为0')
                ->refresh();
        }
        if($add_coin > 0){
            UserUtils::update_user_coins($id, 17, $add_coin, '管理员后台给您增加了'.$add_coin.Settings::get('app_coin_name', '硬币'));
        }else{
            UserUtils::update_user_coins($id, 17, $add_coin, '管理员后台给您减少了'.$add_coin.Settings::get('app_coin_name', '硬币'));
        }
        Cache::forget('get:cached:user:'.$id);
        return $this->response()
            ->success('操作成功.')
            ->refresh();
    }

    /**
     * 构建表单.
     */
    public function form()
    {
        global $__MINI_GLOBAL_IS_ADMIN_SUPER__;
        $the_key = $this->payload["id"];
        if($__MINI_GLOBAL_IS_ADMIN_SUPER__){
            $this->html(function () use ($the_key){
                return '<a href="'.admin_url('coin/record?user_id='.$the_key).'" target="_blank">金币变更记录</a>';
            }, '');
        }
        $this->hidden('id')->value($the_key);
        $this->text('has_coin', '拥有金币')->disable()->default(UserUtils::user_coins($the_key));
        $this->text('add_coin', '增加或减少')->help('减少使用负数')->default(0);
    }

}
